/*
 * MainServerThread.java
 *
 * Created on August 11, 2006, 4:55 PM
 *
 */
package org.letva.copie.subserver.threads;

import java.io.*;
import java.net.*;
import java.util.*;
import java.awt.datatransfer.*;
import java.awt.*;
import org.letva.copie.common.message.Message;
import org.letva.copie.common.message.SubServerInfo;
import org.letva.copie.subserver.*;

/**
 * Nit koja je u stalnoj komunikaciji sa MainServerom. Povremeno (zavisno od delay)
 * my salje poruku, a mainServer odgovara sa listom aktivnih subServera (preko 
 * Message-a)
 * @author Vuk Nikolic
 */
public class MainServerThread extends Thread {

	/**
	 * Creates a new instance of MainServerThread
	 * @param s Socket
	 * @param ms MainServer
	 */
	public MainServerThread(Socket s, SubServer ms) {
		super("MainServerThread");
		mySocket = s;
		mySubServer = ms;
	}

	/**
	 * Metoda u kojoj se sve odvija. Konstantno se vrti u krug (ceka delay) i salje
	 * poruku mainServeru i prima odgovor
	 */
	@Override
	public void run() {
//        System.out.println("MainServerThread: poceo run");
		try {
			ObjectOutput out = new ObjectOutputStream(mySocket.getOutputStream());
			ObjectInput in = new ObjectInputStream(mySocket.getInputStream());

			Object outputMessage = null;
			Object inputMessage = null;

			while (!theEnd) {
				// saljemo poruku da je ovaj subServer ziv
				SubServerInfo me = new SubServerInfo(mySocket.getLocalAddress().toString(),
						mySubServer.getMainServerPort());
				me.setClientPort(mySubServer.getClientPort());
				me.setSubServerPort(mySubServer.getSubServerPort());
				me.setNetworkOperations(mySubServer.getNetworkOperations());

				// postavi stanje clipboarda
				Clipboard myClipboard = Toolkit.getDefaultToolkit().getSystemClipboard();

				if (myClipboard.isDataFlavorAvailable(DataFlavor.stringFlavor) ||
						myClipboard.isDataFlavorAvailable(DataFlavor.javaFileListFlavor)) {
					((SubServerInfo) me).setClipboardStatus(true);
				}


				outputMessage = new Message("subServer", "mainServer", me);

				out.writeObject(outputMessage);
				out.flush();

				inputMessage = (Message) in.readObject();
				inputMessage = myProtocol.messageFromMainServer(inputMessage);

				sleep(delay);
			}


			out.close();
			in.close();
			mySocket.close();

			// ako dodje do exceptiona sa main serverom moramo da obavestimo
			// subserver, posto je centralni server kljucan za komunikaciju
		} catch (SocketTimeoutException ex) {
			mySubServer.writeLog("MainServerThread: SocketTimeoutException: " + ex);
			mySubServer.getMyWindow().setDialogException("Connection Error", "Main server timeout!");
		} catch (SocketException ex) {
			mySubServer.writeLog("MainServerThread: SocketException: " + ex);
			mySubServer.getMyWindow().setDialogException("Connection Error", "Connection to main server is lost!");
		} catch (ClassNotFoundException ex) {
			mySubServer.writeLog("MainServerThread: ClassNotFoundException: " + ex);
			mySubServer.getMyWindow().setDialogException("Internal Error!", "ClassNotFoundException!!!");
		} catch (IOException e) {
			mySubServer.writeLog("MainServerThread: IOException: " + e);
			mySubServer.getMyWindow().setDialogException("Connection Error", "Problems with input/output operations");
		} catch (InterruptedException e) {
		}
		System.out.println("MainServerThread: gotov run");
		// posto vise nema subservera, imamo praznu LinkedListu
		mySubServer.setActiveSubServers(new LinkedList());

		mySubServer.decActiveMainServerThreads();

		mySubServer.getMyWindow().setMainServerStatusLabel("not connected");
		mySubServer.getMyWindow().setConnectToMainServerItem(true);
	}
	/**
	 * Socket sa kojim radi
	 */
	private Socket mySocket = null;
	/**
	 * Poruka od mainServera se obradjuje jednom od metoda Protocol-a
	 */
	private SubServerProtocol myProtocol = SubServer.getProtocol();
	/**
	 * Koliko se ceka u run metodi pre ponovnog slanja
	 */
	private int delay = 10000;
	/**
	 * SubServer na kom je pokrenuta ova nit
	 */
	private SubServer mySubServer = null;
	private boolean theEnd = false;
}
